package com.natalia.excel.listener.normal;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.natalia.excel.utils.EasyExcelValidaHelper;
import com.natalia.excel.utils.SpringBeanUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;

/**
 * @Author yang
 **/
@Slf4j
public class GenericExcelListener<T> extends AnalysisEventListener<T> {


    /**
     * excel对象的反射类
     */
    private Class<?> clazz;

    /**
     * 调用反射方法名
     */
    private String methodName;

    /**
     * 业务接口调用反射类
     */
    private Class<?> serviceClazz;

    /**
     * 批量保存的条数
     */
    private static final int BATCH_COUNT = 0;

    /**
     * 处理结果类
     */
    private GenericExcelResult genericExcelResult;


    public GenericExcelListener(Class<?> serviceClazz,String methodName,GenericExcelResult genericExcelResult,Class<?> clazz) {
        this.clazz = clazz;
        this.methodName = methodName;
        this.serviceClazz = serviceClazz;
        this.genericExcelResult = genericExcelResult;
    }

    @SneakyThrows
    @Override
    public void invoke(T data, AnalysisContext context) {
        //校验数据
        String errMsg = EasyExcelValidaHelper.validateEntity(data,
                context.readRowHolder().getRowIndex() + 1);
        if (ObjectUtils.isNotEmpty(errMsg)){
            genericExcelResult.getErrList().add(errMsg);
        }else {
            //处理数据
            genericExcelResult.getDataList().add(data);
            if (genericExcelResult.getDataList().size()>=BATCH_COUNT){
                Object importService = SpringBeanUtils.getBean(serviceClazz);
                Method serviceMethod = Arrays.stream(importService.getClass().getMethods())
                        .filter(method -> method.getName().equals(methodName))
                        .findFirst()
                        .orElse(null);
                if (serviceMethod != null) {
                    serviceMethod.invoke(importService,genericExcelResult.getDataList());
                }
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 处理所有数据读取完成后的逻辑
        log.info("All data has been read.");
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("single row header validation method.");
        EasyExcelValidaHelper.invokeHeadMap(headMap,clazz);
    }

}

